package org.cll.lagou.study.minicat.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2020/7/2 21:07
 */
public class IStaticResourceUtil {

    private static final Logger logger = LoggerFactory.getLogger(IStaticResourceUtil.class);

    /**
     * 根据请求路径获取静态资源的绝对路径
     * @param path   请求路径
     * @return  绝对路径
     */
    public static String getFileAbsolutePath(String path){
        String rootAbsolutePath = IStaticResourceUtil.class.getResource("/").getPath();
        logger.debug("====== 当前项目绝对路径 = {}", rootAbsolutePath);

        // 返回Http请求中的/形式
        return rootAbsolutePath.replaceAll("\\\\", "/") + path;
    }

    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {

        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }

        int responseResourceSize = count;
        outputStream.write(IHttpProtocolUtil.getHttpResponseHeader200(responseResourceSize).getBytes());

        // 读取输出内容
        long written = 0;
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        while (written < responseResourceSize) {
            if (written + bufferSize > responseResourceSize) {
                bufferSize = (int) (responseResourceSize - written);
                buffer = new byte[bufferSize];
            }

            inputStream.read(buffer);
            outputStream.write(buffer);

            outputStream.flush();
            written += bufferSize;
        }
        outputStream.close();
    }
}